import { computed, reactive, readonly, ref } from 'vue'
import { defineStore, storeToRefs } from 'pinia'
import { useAppStore } from '@/store/app'
import { trackEvent } from '@/gtm'

export const useChatPanelStore = defineStore('chatPanel', () => {
  const onOff = ref(false)
  const feedIdRef = ref(null)
  const user = reactive({
    id: null,
    avatar: null,
    nickname: null,
    isVip: null,
  })

  const isOpen = computed(() => onOff.value)

  const appStore = useAppStore()
  const { isMobile, videoPlay } = storeToRefs(appStore)
  const { toggleViewerExpand, toggleVideoPlay } = appStore

  function open(feed) {
    onOff.value = true
    setFeed(feed)

    toggleViewerExpand(true)

    mobileVideoPause()

    trackEvent({ key: 3, meta: { id: feed.id } })
  }

  function close() {
    onOff.value = false

    mobileVideoRePlay()
  }

  function setFeed(feed) {
    if (!onOff.value) {
      return
    }
    feedIdRef.value = feed.id
    user.id = feed.aff
    user.avatar = feed.author?.avatar
    user.nickname = feed.author?.nickname
    user.isVip = feed.author?.is_vip
  }

  let prevVideoPlay
  function mobileVideoPause() {
    if (isMobile.value) {
      prevVideoPlay = videoPlay.value
      if (prevVideoPlay) {
        toggleVideoPlay()
      }
    }
  }
  function mobileVideoRePlay() {
    if (isMobile.value && prevVideoPlay) {
      toggleVideoPlay(prevVideoPlay)
    }
  }

  return {
    open,
    close,
    setFeed,
    feedId: readonly(feedIdRef),
    user: readonly(user),
    isOpen,
  }
})
